/*******************************************************************************
 * Copyright (c) 2014 Francesco Gabbrielli
 * 
 * All rights reserved. This program and the accompanying materials
 * are made available under the terms of the GNU Public License v2.0
 * which accompanies this distribution, and is available at
 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
 * 
 * Contributors:
 *     Francesco Gabbrielli - initial API and implementation
 ******************************************************************************/
package it.francescogabbrielli.android.solidalapp.file;

import java.util.ArrayList;

import it.francescogabbrielli.android.solidalapp.BaseFragment;
import it.francescogabbrielli.android.solidalapp.ChatMessage;
import it.francescogabbrielli.android.solidalapp.DataEvent;
import it.francescogabbrielli.android.solidalapp.R;
import it.francescogabbrielli.android.solidalapp.ChatMessage.Type;
import it.francescogabbrielli.android.solidalapp.SolidalApp.DataKey;
import it.francescogabbrielli.android.solidalapp.StatusEvent;
import android.content.Context;
import android.media.MediaPlayer;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TextView.OnEditorActionListener;

/**
 * Simple in memory chat
 */
public class ChatFragment extends BaseFragment<FileFragmentListener> 
			implements OnEditorActionListener, OnItemClickListener {
	
	private ChatAdapter adapter;
	
	private MediaPlayer mediaPlayer;
		
	public ChatFragment() {}
	
	private DataKey chatKey;
	
	@Override
	public void onStatusUpdate(StatusEvent event) {
		
	}
	
	@Override
	public void onDataChanged(DataEvent event) {
		
	}
	
	public MediaPlayer getMediaPlayer() {
		if (mediaPlayer==null)
			mediaPlayer = MediaPlayer.create(getActivity(), 
					RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
		return mediaPlayer;
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, 
			Bundle savedInstanceState) {
				
		View view = inflater.inflate(R.layout.fragment_chat, container, false);
		
		EditText e = (EditText) view.findViewById(R.id.chat_edit);
		e.setOnEditorActionListener(this);
		
		FileActivity<?> fa = (FileActivity<?>) getActivity();
		chatKey = fa.getChatKey();

		ListView list = (ListView) view.findViewById(R.id.chat_container);
		list.setOnItemClickListener(this);
		if (adapter==null) {
			@SuppressWarnings("unchecked")
			ArrayList<ChatMessage> array = (ArrayList<ChatMessage>) app.getData(chatKey);
			if (array==null) {
				array = new ArrayList<ChatMessage>();
				app.setData(chatKey, array);
			}
			adapter = new ChatAdapter(getActivity(), array);
		}
		list.setAdapter(adapter);
				
		return view;
	}
	
	@Override
	public void onViewStateRestored(Bundle savedInstanceState) {
		super.onViewStateRestored(savedInstanceState);
		FileActivity<?> fa = (FileActivity<?>) getActivity();

		// execute queued actions
		fa.execChatQueue(this);
	}
						
	@Override
	public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
		if (actionId == EditorInfo.IME_ACTION_SEND) {
			String msg = String.valueOf(v.getText());
			if (!"".equals(msg)) {
				long id = System.currentTimeMillis();
				adapter.add(new ChatMessage(id, msg, ChatMessage.Type.SENDING));
				interactionListener.sendMessage(id, msg);
				v.setText("");
				v.requestFocus();
				InputMethodManager inputManager = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
				inputManager.hideSoftInputFromWindow(v.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
				return true;
			}
		}
		return false;
	}
	
	public void onMessageSent(final long id, final String error) {
		int pos = adapter.getPositionById(id);
		if (pos>=0) {
			ChatMessage m = adapter.getItem(pos);
			if (error==null) {
				m.type = Type.SENT;
			} else {
				m.type = Type.ERROR;
				app.alert(getString(R.string.error_chat_send, error));
			}
			adapter.notifyDataSetChanged();
		}
	}
	
	public void onMessageReceived(String message, boolean isNotification) {
		adapter.notifyDataSetChanged();
		if (!isNotification)
			getMediaPlayer().start();
	}

	@Override
	public void onItemClick(AdapterView<?> listView, View itemView, int position, long id) {
		ChatMessage m = (ChatMessage) adapter.getItem(position);
		if (m.type==Type.ERROR) {
			m.type = Type.SENDING;
			adapter.notifyDataSetChanged();
			interactionListener.sendMessage(m.id, m.text);
		}
	}
}
